package com.sixks.app.mvc.cmd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sixks.app.AliExpressConstant;
import com.sixks.app.api.ApiCallService;
import com.sixks.app.domain.AttrName;
import com.sixks.app.domain.AttrValue;
import com.sixks.app.domain.ExpressUser;
import com.sixks.app.mvc.cmd.exception.ExpressAPIException;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author colin
 * @date: 02/03/2014
 * @time: 20:57
 */
public class AttributeByCategoryId extends BaseCommandAPI<APIRequest> {

    @Override
    protected APIResponse handle(APIRequest request, ExpressUser user) {

        //Load file
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("category_raw.sql");
        List<IDN> ids = new ArrayList<IDN>();
        Pattern p = Pattern.compile("\\([0-9]+");
        Pattern p1 = Pattern.compile("\\([0-9]+,'.*'");

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = reader.readLine();
            while (line != null) {
                String newLine = "";
                if (line.startsWith("#")) {
                    System.out.println(line);
                    line = reader.readLine();
                    continue;
                }
                newLine = line.replaceAll("parent", "parent,isleaf");
                if (line.contains("isleaf:false")) {
                    newLine = newLine.replace(");##isleaf:false", ",'false');");
                }
                if (line.contains("isleaf:true")) {
                    newLine = newLine.replace(");##isleaf:true", ",'true');");
                    Matcher matcher = p.matcher(line);
                    int id = 0;
                    if (matcher.find()) {
                        id = Integer.valueOf(matcher.group().substring(1));
                    }
                    String name = "";
                    matcher = p1.matcher(line);
                    if (matcher.find()) {
                        String ss = matcher.group();
                        int idx1 = ss.lastIndexOf(",");
                        int idx2 = ss.indexOf(",");
                        name = ss.substring(idx2 + 1, idx1);
                    }
                    ids.add(new IDN(name, id));
                }
                System.out.println(newLine);
                line = reader.readLine();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (IDN id : ids) {
            retrieve(id.getId(), id.getName(), user.getAccessToken());
//            try {
//                Thread.sleep(500);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
        System.out.println("done!");
        return null;
    }

    class IDN {
        private String name;
        private int id;

        public IDN(String name, int id) {
            this.name = name;
            this.id = id;
        }

        String getName() {
            return name;
        }

        void setName(String name) {
            this.name = name;
        }

        int getId() {
            return id;
        }

        void setId(int id) {
            this.id = id;
        }
    }

    private void retrieve(int cateId, String cateName, String token) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("cateId", String.valueOf(cateId));
        params.put("access_token", token);
        String json = null;
        try {
            json = ApiCallService.callApiTest(HTTP_ROOT, "param2/1/aliexpress.open/api.getAttributesResultByCateId/" + AliExpressConstant.APP_KEY, AliExpressConstant.SIGN, params);
        } catch (ExpressAPIException e) {
            e.printStackTrace();
        }
        print(json, cateId, cateName);
    }

    private void print(String json, int cateId, String cateName) {
        Map map = JSON.parseObject(json, Map.class);
        JSONArray array = (JSONArray) map.get("attributes");
        List<AttrName> names = new ArrayList<AttrName>();
        for (Object anArray : array) {
            JSONObject jobj = (JSONObject) anArray;
            AttrName attrName = JSON.toJavaObject(jobj, AttrName.class);
            names.add(attrName);
        }
        String fileName = "/Users/colin/Documents/sql_attr.sql";
        for (AttrName attrName : names) {
            if(attrName.getRequired().equals("false")){
                continue;
            }
            System.out.println("INSERT INTO attrname(cateId,cateName,cateNameId,cateNameZh,cateNameEN) values(" + cateId + ",'" + cateName + "'," + attrName.getId() + ",'" + attrName.getNamesZh() + "','" + attrName.getNamesEn() + "');");
            writeFile(fileName, "INSERT INTO attrname(cateId,cateName,cateNameId,cateNameZh,cateNameEN) values(" + cateId + ",'" + cateName + "'," + attrName.getId() + ",'" + attrName.getNamesZh() + "','" + attrName.getNamesEn() + "');");

            for (AttrValue value : attrName.getAttrValues()) {
                System.out.println("INSERT INTO attrvalue(belongTo,valId,valZh,valEN) values(" + attrName.getId() + "," + value.getId() + ",'" + value.getZh() + "','" + value.getEn() + "');");
                writeFile(fileName, "INSERT INTO attrvalue(belongTo,valId,valZh,valEN) values(" + attrName.getId() + "," + value.getId() + ",'" + value.getZh() + "','" + value.getEn() + "');");
            }
        }
    }

    public static void writeFile(String file, String content) {

        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file, true)));
            out.write(content + "\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert out != null;
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
